define(function(require, exports){
	var pubjs = require('pubjs');
	var $ = require('jquery');
	var grid = require('@base/highGrid');
	var util = require('util');

	var STATUS = pubjs.config('CONST/OFFLINE_STATUS');
	var TYPE = pubjs.config("CONST/OFFLINE_TYPE");
	// 报表中心
	var ReportCenter = grid.base.extend({
		init: function(config){
			config = pubjs.conf(config, {
					url: 'groupDim/list',
					param: {
						'IsDeleted': false
					},
					cols: [
						{"type":"id"},
						{"name":"Status","type":"index", "render": "renderStatus"},
						{"name":"date","type":"index","text":LANG("日期"),render:'renderDate', width:200},
						{"name":"Deal","type":"index","text":LANG("订单"),"render":"renderDeal",width:200},
						{"name":"Campaign","type":"index","text":LANG("活动"),"render":"renderCampaign",width:200},
						{"name":"Sweety","type":"index","text":LANG("创意包"),"render":"renderCreative",width:200},
						{"name":"Whisky","type":"index","text":LANG("落地页"),"render":"renderWhisky",width:200},
						{"name":"Channel","type":"index","text":LANG("渠道")},
						{"name":"hour","type":"index","text":LANG("时段"),width:200},
						{"name":"Region","type":"index","text":LANG("地区"),"render":"renderZone",width:200},
						{"name":"Advertiser", "type":"index", "text":LANG("广告位"), "render": "renderAdvertiser",width:200},
						{"name":"page_channel_id","text":LANG("一级频道分类ID"),"format": "numberFormat"},
						{"name":"ChannelCategory", "text":LANG("一级频道分类"),"render": "renderChannelCategory"},
						{"name":"page_channel2_id","text":LANG("二级频道分类ID"),"format": "numberFormat"},
						{"name":"ChannelCategory2", "text":LANG("二级频道分类"),"render": "renderChannelCategory"}
					],
					// 也有竞价组
					tab: pubjs.config('metricsGroup/mixDimension/tabs'),
					default_metrics : pubjs.config('defaultMetrics'),
					hasSwitch: false,
					hasSubGrid: false,
					reqType: 'websocket',
					gridName: 'groupDim'
				}
			);
			this.Super('init', arguments);
		},
		renderStatus:function(i, val, data, con){
			// @todo 如果没有此字段，要隐藏
			var text = (+data.Status == 1) ? LANG('已开启'): LANG('已暂停');
			var className = (+data.Status == 1) ? 'runing': 'suspend';
			return '<div class="G-iconFunc '+className+'" title="'+text+'">';
		},
		renderCampaign: function(i, val, data, con){
			var dom = $('<div class="M-tableListWidthLimit"/>').width(con.width);
			$('<a target="_blank"  href="#campaign/edit/'+data.campaign_id+'"/>').text(val).appendTo(dom);
			return dom;
		},
		renderCreative: function(i, val, data, con){
			var dom = $('<div class="M-tableListWidthLimit"/>').width(con.width);
			var url = pubjs.config('materialPreview/sweety');
			url = url.replace('{id}', data.package_id);
			$('<a target="_blank"  href="'+url+'"/>').text(val).appendTo(dom);
			return dom;
		},
		renderWhisky: function(i, val, data, con){
			var url = pubjs.config('materialPreview/whisky');
			url = url.replace('{id}', data.whisky_id);
			var dom = $('<div class="M-tableListWidthLimit"/>').width(con.width);
			$('<a target="_blank"  href="'+url+'"/>').text(val).appendTo(dom);
			return dom;
		},
		renderZone: function(i, val, data, con){
			var path = window.ROOT('resources/images/geo/');
			path = data.country_icon ? path+data.country_icon : '';
			var html = '';
			if(data.country_icon){
				html  = '<i class="vmiddle"><img src="'+path+'.png" alt=""> '+data.country_name+" "+data.region_name+'</i>';
			}
			return html;
		},
		renderDate: function(i, val, data, con){
			return $('<div />').text(val).width(con.width);
		},
		renderDeal: function(i, val, data, con){
			val = val || '-';
			return $('<div class="uk-text-truncate tl fl" title="'+val+'">'+val+'</div>').width(con.width-20);
		},
		renderChannelCategory: function(i, val, data, con)
		{
			return val || '-';
		},
		renderAdvertiser: function(i, val, data, con)
		{
			return val || '-';
		}
	});
	exports.base = ReportCenter;
	var TYPE = {
		COMMON: 1, SCHEDULE: 3
	};
	var TIME_TYPE = {
		DAY: 0, WEEK: 1, MONTH: 2
	};
	// 自定义报表
	var CustomReport = grid.base.extend({
		init: function(config){
			config = pubjs.conf(config, {
					url: 'customDownload/list',
					exportUrl : '/api/dsp/download/offline/', //需要一个下载路由
					cols: [
						{name:'_id',text:"ID", sort: true, align: 'center', width: 60},
						{name:'Name',text:LANG("报表名字"), align: 'left',render: 'renderName', width: 200},
						{name:'Status',text:LANG("状态"), render: 'renderStatus', align: 'left',width:60},
						{name:'Condition',text:LANG("报表类型"), render: 'renderType', align: 'center', width: 100},
						{name:'Condition',text:LANG("时间段"), render: 'renderPeriod', align: 'center',width:240},
						{name:'download',text:LANG("选择下载"), render: 'renderDownload', align: 'center',width:100},
					]
					,"metrics": [
						{name:'CreateTime',text:LANG("创建时间"), render: 'renderCreateTime', align: 'center' ,width: 200},
						{name:'Time',text:LANG("消耗时间"), render: 'renderTime', align: 'center',width:60}, //这个没接口
						{name:'Condition',text:LANG("广告主"), render: 'renderAdv',align: 'left'}
					],
					hasAmount: false,
					hasTab: false,
					hasMenu: true,
					hasExport: false,
					hasBatch: false,
					hasSelect: false,
					isSendMetrics: false,
					hasAutoRefresh: true,
					refreshAuto: 1,		// 自动刷新中
					refreshCheckToday: false, // 刷新时会检查今天
					reqType: 'websocket',
					gridName: 'customReport',
					hasSubGrid:true,
					hasFilter:false
				}
			);
			this.Super('init', arguments);
		}
		,renderName: function(i, val){
			return $('<div class="text-truncate "/>').text(val).attr('title', val);
		}
		,renderPeriod: function(data, val)
		{
			val = val.Date;
			switch (val.Type){
				case TYPE.COMMON :
					var begin = util.date("Y年m月d日", val.Param.begin);
					var end = util.date("Y年m月d日", val.Param.end);
					return begin + ' ~ ' + end;
				case TYPE.SCHEDULE :
					switch (val.Param.Type){
						case TIME_TYPE.DAY:
							return LANG('每日0点');
						case TIME_TYPE.WEEK:
							return LANG('每周'+val.Param.name);
						case TIME_TYPE.MONTH:
							if(val.Param.id!=="293031"){
								return LANG('每月第'+val.Param.name);
							}else{
								return LANG('每月'+val.Param.name);
							}
					}
			}
			return '--';
		}
		,renderAdv: function(i, val, data)
		{
			val = val.Adv;
			var advString = '';
			var limit = 8;
			util.each(val ,function (item,idx) {
				if(idx > limit){
					return;
				}
				if(idx === limit) {
					advString += ' ...';
				}
				else if(idx!==0 && idx < limit){
					advString += "、";
				}
				if(idx < limit){
					advString += '('+item.id+" |"+item.name+')';
				}
			});
			return advString;
		}
		,renderStatus: function(i, val, data)
		{
			if(data.Type == TYPE.SCHEDULE) {
				return "-";
			}
			
			var str = LANG('未知');
			switch (val)
			{
				case STATUS.DONE:
					str = LANG('已完成');
					break;
				case STATUS.FAIL:
					str = LANG('下载失败: ') + data.Info;
					break;
				case STATUS.WAIT:
					str = LANG('待下载');
					break;
				case STATUS.ING:
					str = LANG('进行中');
					break;
				case STATUS.PAUSE:
					str = LANG('已中止');
					break;
			}

			return $('<div class="text-truncate"/>').text(str).attr('title', str);
		}
		,renderTime: function(data, val)
		{
			if(val)
			{
				return Math.round(val/1000, 2) + LANG('秒');
			}
			else
			{
				return '--';
			}
		}
		,renderCreateTime: function(i, val, data)
		{
			if(data.CreateTime)
			{
				return util.date("Y年m月d日", data.CreateTime);
			}
			else
			{
				return '--';
			}
		},
		renderType: function (i,val) {
			switch(val.Date.Type){
				case TYPE.COMMON :
					return LANG('普通报表');
				case TYPE.SCHEDULE :
					return LANG('定时报表');
			}
		}
		,renderDownload: function(i, val, data, con) {
			var self = this;
			var c = this.getConfig();
			switch(data.Condition.Date.Type){
				case TYPE.COMMON :
					var canDownload = data.Status === STATUS.DONE && pubjs.checkRight('customDownload.download');
					var url = c.exportUrl + data._id;
					var cla = canDownload ? '' : 'disabled font-gray';
					return `<a class="${cla}" href="${canDownload ? url : 'javascript:void(0)'}">${LANG('下载')}</a>`;
				case TYPE.SCHEDULE :
					var html = $('<a href="javascript:void(0)" title="弹出框"/>').text(LANG('下载')).click(function () {
						self.fire('showSchedule',data);
					});
					return html;
			}
		}
	});
	exports.customReport = CustomReport;
	// 定时报表
	var TimeReport = grid.base.extend({
		init: function(config){
			config = pubjs.conf(config, {
				url: 'customDownload/scheduleList', // 需要一个参数id的定时报表
				param: {},
				exportUrl : '/api/dsp/download/offline/', //需要一个下载路由
				cols: [
					{name:'file',text:LANG("名称"), align: 'left',width: 200},
					{name:'download',text:LANG("下载"), render: 'renderDownload', align: 'center',width:100},
				],
				pager: {
					size: 10
				},
				hasSearch: false,
				hasAmount: false,
				hasTab: false,
				hasMenu: false,
				hasExport: false,
				hasBatch: false,
				hasSelect: false,
				isSendMetrics: false,
				reqType: 'websocket',
				gridName: 'customReport',
				hasSubGrid:false,
				hasFilter:false
			});
			
			this.Super('init', arguments);
		}
		,renderDownload: function(i, val, data, con) {
			var c = this.getConfig();
			var param = this.getParam();
			var url = c.exportUrl + param._id+ '?file='+data.file;
			return `<a class="" href="${url}">${LANG('下载')}</a>`;
		},
	});
	exports.timeReport = TimeReport;
});